<?php

namespace MoChat\App\Home\Action;

use Hyperf\DbConnection\Db;
use MoChat\App\WorkDepartment\Contract\WorkDepartmentContract;
use MoChat\Framework\Action\AbstractAction;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Sales\Constants\SalesTaskStatusCode;
use MoChat\App\Sales\Contract\SalesClientTaskContract;
use MoChat\App\Sales\Contract\SalesClientTaskEmployeeContract;
use MoChat\App\Sales\Contract\SalesTaskContract;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Constants\ErrorCode;

/**
 * 成交订单数排行榜
 * @Controller
 */
class DealOrderRanking extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkDepartmentContract
     */
    protected $workDepartmentService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     * @RequestMapping(path="/dashboard/home/dealOrderRanking", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $this->validated($data);
        $startTime = "2021-06-01 00:00:00";
        $endTime = date('Y-m-d H:i:s');
        if (!empty($data['time_enum']) && is_numeric($data['time_enum'])) {
            switch ($data['time_enum']) {
                //年
                case 1:
                    $startTime = date('Y-01-01 00:00:00');
                    $endTime = date('Y-m-d H:i:s');
                    break;
                //月
                case 2:
                    $startTime = date('Y-m-01 00:00:00');
                    $endTime = date('Y-m-d H:i:s');
                    break;
                //日
                case 3:
                    $startTime = date('Y-m-d 00:00:00');
                    $endTime = date('Y-m-d H:i:s');
                    break;
                default:
            }
        }
        $type=$data['type']??0;
        if ($type==0){
            return Db::connection('b2b')->table('salesman')
                ->join('place_order_assign_manager as assign', 'assign.SALESMAN_ID', '=', 'salesman.ID')
                ->join('user_order as order', 'order.ID', '=', 'assign.ORDER_ID')
                ->join('order_status as status', 'status.ID', '=', 'order.ID')
                ->where('order.CREATE_TIME', '>=',$startTime)
                ->where('order.CREATE_TIME', '<',$endTime)
                ->where('status.PAYMENT', 1)
                ->select([
                    'salesman.ID as id',
                    'salesman.USER_NAME AS name',
                    Db::raw('COUNT(DISTINCT my_order.ID) as count'),
                ])
                ->limit(10)
                ->orderBy('count','desc')
                ->groupBy([
                    'salesman.ID',
                ])->get()->toArray();
        }

        return Db::connection('b2b')->table('salesman')
            ->join('place_order_assign_manager as assign', 'assign.SALESMAN_ID', '=', 'salesman.ID')
            ->join('user_order as order', 'order.ID', '=', 'assign.ORDER_ID')
            ->join('order_status as status', 'status.ID', '=', 'order.ID')
            ->where('order.CREATE_TIME', '>=',$startTime)
            ->where('order.CREATE_TIME', '<',$endTime)
            ->where('status.PAYMENT', 1)
            ->select([
                'salesman.ID as id',
                'salesman.USER_NAME AS name',
                Db::raw('SUM(my_order.TOTAL_AMOUNT) as count'),
            ])
            ->limit(10)
            ->orderBy('count','desc')
            ->groupBy([
                'salesman.ID',
            ])->get()->toArray();
    }

    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [
            'time_enum' => 'in:1,2,3',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected function messages(): array
    {
        return [
            'time_enum.in' => 'time_enum参数错误',
        ];
    }
}
